package com.example.harmans;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

class GetinternetData extends AsyncTask<String, Void, String>{
	
	String[][] stringArray;
	String result = null;
	
	private static final String TAG = "MainActivity";
    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        InputStream inputStream = null;
        HttpGet httpget = new HttpGet("http://www.mtcodelab.com/Development/harmans/blog");
        System.out.println("HERE1");
        try{
            HttpResponse response = httpclient.execute(httpget);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            System.out.println("HERE2");
            if(statusCode == 200){
                HttpEntity entity = response.getEntity();
                inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                String line = null;
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                	sb.append(line + "\n");

                result = sb.toString();
                System.out.println("RESULT INNER = "+result);
                return result;
            }else{
                Log.d(TAG, "Couldn't connect");
            }
        }catch(Exception e){
            Log.d(TAG, e.toString());
        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }
        try {
			JSONArray array = new JSONArray(result);
			stringArray = new String[array.length()][6];
			for (int i = 0; i < array.length(); i++) {
				JSONObject row = array.getJSONObject(i);
				stringArray[i][0] = row.getString("id");
				stringArray[i][1] = row.getString("title");
				stringArray[i][2] = row.getString("address");
				stringArray[i][3] = row.getString("number");
				stringArray[i][4] = row.getString("link");
				stringArray[i][5] = row.getString("description");

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        //message.setText("Postsequence");
    }   
}